<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>在排序数组中查找元素的第一个位置和最后一个位置</title>
</head>
<body>
  <script>
    function fn(nums, target) {
      let left = 0, right = nums.length - 1, mid;
      while (left <= right) { // 二分查找target
        mid = (left + right) >> 1;
        if (nums[mid] === target) break;
        if (nums[mid] > target) right = mid - 1;
        else left = mid + 1;
      }
      if (left > right) return [-1, -1]
      let i = mid, j = mid;
      while (nums[i] === nums[i - 1]) i--; // 向左尝试找相同的元素
      while (nums[j] === nums[j + 1]) j++; // 向右尝试找相同的元素
      return [i, j]
    }
    console.log(fn([5, 7, 7, 8, 8, 10], 8))
  </script>
</body>
</html>